#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
检查所有服务状态的脚本
"""

import requests
import subprocess
import time
import os

def check_redis():
    """检查Redis服务"""
    try:
        import redis
        r = redis.Redis(host='localhost', port=6379, db=0)
        r.ping()
        print("✓ Redis 服务正常")
        return True
    except Exception as e:
        print(f"✗ Redis 服务异常: {e}")
        return False

def check_django():
    """检查Django服务"""
    try:
        response = requests.get('http://localhost:3000/admin/', timeout=5)
        if response.status_code in [200, 302, 404]:  # 404也是正常的，说明Django在运行
            print("✓ Django 服务正常")
            return True
        else:
            print(f"✗ Django 服务异常，状态码: {response.status_code}")
            return False
    except requests.exceptions.ConnectionError:
        print("✗ Django 服务未启动或端口不正确")
        return False
    except Exception as e:
        print(f"✗ Django 服务检查失败: {e}")
        return False

def check_celery():
    """检查Celery服务"""
    try:
        # 检查是否有celery进程在运行
        if os.name == 'nt':  # Windows
            result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq python.exe'], 
                                  capture_output=True, text=True)
        else:  # Linux/Mac
            result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        
        if 'celery' in result.stdout:
            print("✓ Celery 服务正在运行")
            return True
        else:
            print("✗ Celery 服务未运行")
            return False
    except Exception as e:
        print(f"✗ Celery 服务检查失败: {e}")
        return False

def test_api_endpoints():
    """测试API端点"""
    print("\n=== 测试API端点 ===")
    
    endpoints = [
        ('http://localhost:3000/verify/qutoken/', 'GET', '七牛云Token接口'),
        ('http://localhost:3000/api/userinfo/', 'GET', '用户信息接口'),
        ('http://localhost:3000/api/logout/', 'POST', '退出登录接口'),
    ]
    
    for url, method, name in endpoints:
        try:
            if method == 'GET':
                response = requests.get(url, timeout=5)
            else:
                response = requests.post(url, timeout=5)
            
            print(f"{name}: {response.status_code}")
            
            if response.status_code == 500:
                print(f"  ✗ 服务器内部错误: {response.text[:200]}")
            elif response.status_code in [200, 201, 302, 401, 403]:
                print(f"  ✓ 接口响应正常")
            else:
                print(f"  ⚠️ 异常状态码: {response.status_code}")
                
        except requests.exceptions.ConnectionError:
            print(f"{name}: ✗ 连接失败")
        except Exception as e:
            print(f"{name}: ✗ 请求失败 - {e}")

def main():
    """主函数"""
    print("=== 服务状态检查 ===")
    print()
    
    # 检查各个服务
    redis_ok = check_redis()
    django_ok = check_django()
    celery_ok = check_celery()
    
    print()
    
    # 如果Django正常，测试API
    if django_ok:
        test_api_endpoints()
    
    print()
    print("=== 检查结果 ===")
    print(f"Redis: {'✓' if redis_ok else '✗'}")
    print(f"Django: {'✓' if django_ok else '✗'}")
    print(f"Celery: {'✓' if celery_ok else '✗'}")
    
    if not all([redis_ok, django_ok]):
        print("\n🔧 建议操作:")
        if not redis_ok:
            print("1. 启动Redis: redis-server")
        if not django_ok:
            print("2. 启动Django: python manage.py runserver 0.0.0.0:3000")
        if not celery_ok:
            print("3. 启动Celery: celery -A keep_project0 worker --loglevel=info --pool=solo")
            print("4. 启动Celery Beat: celery -A keep_project0 beat --loglevel=info")
        
        print("\n或者使用启动脚本: python start_services.py")

if __name__ == "__main__":
    main()

